package com.ho1ho.springboot.framework.core.interceptors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ho1ho.springboot.framework.core.Const;
import com.ho1ho.springboot.framework.core.auth.AuthSecurityService;
import com.ho1ho.springboot.framework.core.auth.iters.UserDetail;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class GlobalEnvironmentInterceptor implements HandlerInterceptor {

	// @Value("${spring.profiles.active}")
	// private String activeProfile;

	@Resource
	private AuthSecurityService authSecurityServiceImpl;

	private UserDetail userDetail;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// log.trace("GlobalEnvironmentInterceptor preHandle");
		if (userDetail == null) {
			log.warn("UserDetail is null.");
			return false;
		}

		// log.debug("Activate Profile: {}", activeProfile);
		// request.setAttribute("activeProfile", activeProfile);
		User user = authSecurityServiceImpl.getLoggedInUser();
		log.debug("LoggedIn User: {}", user);
		request.setAttribute(Const.LOGGED_IN_USER, user);

		HttpSession session = request.getSession(false);
		if (session != null) {
			Object sessionUser = session.getAttribute(Const.USER_IN_SESSION);
			if (sessionUser == null && user != null && StringUtils.isNotBlank(user.getUsername())) {
				log.debug("Session user is null. Get it from db according to loggedInUser then set it to session again - User {}", user);
				sessionUser = userDetail.getUserBean(user.getUsername());
				session.setAttribute(Const.USER_IN_SESSION, sessionUser);
			}
			log.debug("LoggedIn Session User: {}", sessionUser);
		}
		return true;
	}

	// @Override
	// public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
	// modelAndView) throws Exception {
	// log.trace("GlobalEnvironmentInterceptor postHandle");
	// }
	//
	// @Override
	// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
	// throws Exception {
	// log.trace("GlobalEnvironmentInterceptor afterCompletion");
	// }

	public void setUserDetail(UserDetail userDetail) {
		this.userDetail = userDetail;
	};
}